package com.inhim.pjhim.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.inhim.pjhim.R;
import com.inhim.pjhim.adapter.DialogRecViewAdapter;
import com.inhim.pjhim.adapter.HorizontalRecViewAdapter;
import com.inhim.pjhim.adapter.TypeListAdapter;
import com.inhim.pjhim.app.BaseActivity;
import com.inhim.pjhim.entity.ReaderTypeList;
import com.inhim.pjhim.fragment.CollectionFragment;
import com.inhim.pjhim.fragment.CollectionRadioFragment;
import com.inhim.pjhim.fragment.CollectionReadFragment;
import com.inhim.pjhim.fragment.TypeListFragment;
import com.inhim.pjhim.http.MyOkHttpClient;
import com.inhim.pjhim.http.Urls;
import com.inhim.pjhim.utils.RecylerViewUtils;
import com.inhim.pjhim.view.NoScrollViewPager;

import org.yczbj.ycrefreshviewlib.view.YCRefreshView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Request;

public class TypeListActivity extends BaseActivity {
    private ReaderTypeList.List ReaderType;
    private List<ReaderTypeList.List> ReaderTypeList;
    private Gson gson;
    private String TAG, Title;
    private TextView tv_title;
    private ImageView iv_back;
    private RecyclerView horizontal_rec_view;
    private HorizontalRecViewAdapter horizontalRecViewAdapter;
    private int mAdapterPsition;
    private ImageView mTvDropDown;
    private LinearLayout lin_dialog, lin_dialog_child;
    private RecyclerView recy_dialog;
    private TextView tv_dialog_name;
    private View background_dialog;
    private DialogRecViewAdapter mDialogRecViewAdapter;
    private String mType;
    private int mParentId;
    private int mReaderTypeId;
    private boolean mIsFirst;
    private NoScrollViewPager mViewPager;
    private ArrayList<Fragment> fs;

    @Override
    public Object offerLayout() {
        return R.layout.activity_type_list;
    }

    @SuppressLint("NewApi")
    @Override
    public void onBindView() {
        gson = new Gson();
        mViewPager = findViewById(R.id.viewPager);
        horizontal_rec_view = findViewById(R.id.horizontal_rec_view);
        TAG = getIntent().getStringExtra("TAG");
        mAdapterPsition = getIntent().getIntExtra("position", 0);
        mType = getIntent().getStringExtra("Type");
        Title = getIntent().getStringExtra("Title");
        //mParentId=getIntent().getIntExtra("ParentId",0);
        mReaderTypeId = getIntent().getIntExtra("ReaderTypeId", 0);
        if (TAG.equals("ReadingTwoFragment")) {
            ReaderType = (ReaderTypeList.List) getIntent().getSerializableExtra("ReaderType");
            ReaderTypeList = (List<ReaderTypeList.List>) getIntent().getSerializableExtra("ReaderTypeList");
        }else {
            getReaderTypeList();
        }
        if (mReaderTypeId != 0) {
            mIsFirst = true;
        }
        iv_back = findViewById(R.id.iv_back);
        tv_title = findViewById(R.id.tvCourse);
        mTvDropDown = findViewById(R.id.tv_drop_down);
        lin_dialog = findViewById(R.id.lin_dialog);
        lin_dialog_child = findViewById(R.id.lin_dialog_child);
        recy_dialog = findViewById(R.id.recy_dialog);
        tv_dialog_name = findViewById(R.id.tv_dialog_name);
        tv_dialog_name.setText(Title + "分类");
        background_dialog = findViewById(R.id.background_dialog);
        /*background_dialog.setBackgroundColor(Color.BLACK);
        background_dialog.getBackground().setAlpha(50);*/
        if (ReaderTypeList != null && ReaderTypeList.size() > 5) {
            mTvDropDown.setVisibility(View.VISIBLE);
        }
        //lin_dialog_child.setOnClickListener(null);
        mTvDropDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lin_dialog.setVisibility(View.VISIBLE);
                background_dialog.setVisibility(View.VISIBLE);
            }
        });
        background_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lin_dialog.setVisibility(View.GONE);
                background_dialog.setVisibility(View.GONE);
            }
        });
        tv_title.setText(Title);
        iv_back.setOnClickListener(v -> finish());
        initAdapter();
        setFragment();
    }

    private void setFragment() {
        if(ReaderTypeList==null || ReaderTypeList.size()==0){
            return;
        }
        fs = new ArrayList<>();
        FragmentManager fm = getSupportFragmentManager();
        MyPagerAdapter adapter = new MyPagerAdapter(fm);
        for (int i=0;i<ReaderTypeList.size();i++){
            Bundle bundle = new Bundle();
            bundle.putSerializable("Type", mType);
            bundle.putSerializable("TAG", TAG);
            ReaderType = ReaderTypeList.get(i);
            bundle.putSerializable("ReaderType", ReaderType);
            TypeListFragment typeListFragment=new TypeListFragment();
            typeListFragment.setArguments(bundle);
            fs.add(typeListFragment);
            mViewPager.setAdapter(adapter);
            mViewPager.setCurrentItem(mAdapterPsition);
        }
        mViewPager.setOffscreenPageLimit(15);
        setListener();
    }

    private void setListener() {
        // TODO Auto-generated method stub
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            public void onPageSelected(int position) {
                horizontal_rec_view.scrollToPosition(position);
                horizontalRecViewAdapter.notfyPosition(position);
            }

            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            public void onPageScrollStateChanged(int arg0) {

            }
        });
    }


    /**
     * 自定义适配器  FragmentPagerAdapter
     */
    class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int arg0) {
            return fs.get(arg0);
        }

        @Override
        public int getCount() {
            return fs.size();
        }
    }

    @Override
    public void destory() {

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initAdapter() {

        horizontalRecViewAdapter = new HorizontalRecViewAdapter(TypeListActivity.this, mAdapterPsition);
        horizontal_rec_view.setAdapter(horizontalRecViewAdapter);
        if (ReaderTypeList != null) {
            horizontalRecViewAdapter.addAll(ReaderTypeList);
            horizontalRecViewAdapter.notifyDataSetChanged();
            horizontal_rec_view.scrollToPosition(mAdapterPsition);
        }
        RecylerViewUtils.attachLinearRv(TypeListActivity.this, horizontal_rec_view, RecylerViewUtils.HORIZONTAL, mAdapterPsition);
        horizontalRecViewAdapter.setItemOnClickListener(new HorizontalRecViewAdapter.ItemOnClickListener() {
            @Override
            public void onClick(int position) {
                mViewPager.setCurrentItem(position);
            }
        });

        mDialogRecViewAdapter = new DialogRecViewAdapter(TypeListActivity.this, mAdapterPsition);
        recy_dialog.setAdapter(mDialogRecViewAdapter);
        if (ReaderTypeList != null) {
            mDialogRecViewAdapter.addAll(ReaderTypeList);
            mDialogRecViewAdapter.notifyDataSetChanged();
            recy_dialog.scrollToPosition(mAdapterPsition);
        }
        RecylerViewUtils.attachLinearRv(TypeListActivity.this, recy_dialog, RecylerViewUtils.GRID, mAdapterPsition);
        mDialogRecViewAdapter.setItemOnClickListener(position -> {
            ReaderType = ReaderTypeList.get(position);
            lin_dialog.setVisibility(View.GONE);
            background_dialog.setVisibility(View.GONE);
            mAdapterPsition = position;
            horizontal_rec_view.scrollToPosition(mAdapterPsition);
            horizontalRecViewAdapter.notfyPosition(mAdapterPsition);
            mViewPager.setCurrentItem(position);
        });
    }

    private void getReaderTypeList() {
        //showLoading("加载中");
        HashMap postMap = new HashMap();
        String url = Urls.getReaderTypeList(1, 50, mType, mParentId);
        MyOkHttpClient.getInstance().asyncJsonPostNoToken(url, postMap, new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
                //hideLoading();
            }

            @Override
            public void onSuccess(Request request, String result) {
                //hideLoading();
                try {
                    ReaderTypeList readerLists = gson.fromJson(result, ReaderTypeList.class);
                    if (readerLists.getCode() == 0) {
                        ReaderTypeList = readerLists.getPage().getList();
                        horizontalRecViewAdapter.addAll(ReaderTypeList);
                        if (mReaderTypeId != 0 && mIsFirst) {
                            for (int i = 0; i < ReaderTypeList.size(); i++) {
                                if (mReaderTypeId == ReaderTypeList.get(i).getReaderTypeId()) {
                                    mAdapterPsition = i;
                                    horizontalRecViewAdapter.notfyPosition(mAdapterPsition);
                                }
                            }
                        } else {
                            horizontalRecViewAdapter.notifyDataSetChanged();
                        }
                        mIsFirst = false;
                        ReaderType = ReaderTypeList.get(mAdapterPsition);
                        horizontal_rec_view.scrollToPosition(mAdapterPsition);
                        mDialogRecViewAdapter.addAll(ReaderTypeList);
                        mDialogRecViewAdapter.notifyDataSetChanged();
                        recy_dialog.scrollToPosition(mAdapterPsition);
                        if (ReaderTypeList != null && ReaderTypeList.size() > 5) {
                            mTvDropDown.setVisibility(View.VISIBLE);
                        }
                        setFragment();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
